<!DOCTYPE html>
<html lang="zh-Hans">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
    <title>OpenWrt Print&Scan项目</title>
    <link rel="stylesheet" href="./static/iceui/src/ui/ui.css"/>
    <script src="./static/iceui/src/ice.js"></script>
    <script src="./static/iceui/src/ui/ui.js"></script>
	<!-- 引入axios -->
	<script src="./static/axios.js"></script>
</head>
<body>
	<div id="app">
	<!-- 添加面包屑菜单 -->
	<div class="title-l">SANEScan</div>
	<div class="breadcrumb">
		<a href="/">首页</a>
		<a href="/">扫描</a>
		文件扫描(SANE方式)
		<a href="/" class="back">返回首页</a>
	</div>
	<div class="title-l">扫描设置</div>
	<div class="group-form">
		<div class="group-label">扫描设备</div>
		<div class="group-content">
			<select class="select" id="scan-device" title="请选择设备" >
				{{range $item := .deviceList}}
					<option value="{{$item.Value}}">{{$item.Name}}</option>
				{{end}}
			</select>
		</div>
		<div class="group-label">扫描分辨率</div>
		<div class="group-content">
			<select class="select" id="scan-dpi">
				<!-- <option value="300">300 dpi</option> -->
				<option value="150">150 dpi</option>
				<option value="100">100 dpi</option>
				<option value="75">75 dpi</option>
				<option value="60">60 dpi</option>
				<option value="50">50 dpi</option>
				<option value="43">43 dpi</option>
				<option value="37">37 dpi</option>
			</select>
		</div>
		<div class="group-label">扫描模式</div>
		<div class="group-content">
			<select class="select" id="scan-mode">
				<option value="Color">彩色</option>
				<option value="Gray">灰度</option>
			</select>
		</div>
    </div>
	<div class="group-form">
		<div class="group-label">导出文件名</div>
		<div class="group-content">
			<input type="text" class="form-control" id="scan-filename" placeholder="请输入">
			<small class="help">建议20个字符以内，不填写则默认使用日期作为文件名</small>
		</div>
	</div>
	<div>
		<button type="button" class="btn bg-black btn-ani btn-block" onclick="startScan()"><span>开始扫描<i></i></span></button>
	</div>
	<div class="progress" id="scan-process" style="display: none;">
		<div class="progress-bar progress-stripe progress-ani progress-black" style="width:54%;" id="scan-processBar">
			54%</div>
	</div>
	<div class="boxLoading" style="display: none;" id="box-loading"></div>
	<div class="title-l">已扫描的项目(点击图片可预览)</div>
	<section class="section-box">
		<div class="page">
			<div class="row">
				{{range $name := .itemList}}
				<div class="ws6 wm6 w3">
					<div class="grid-team">
						<div class="grid-img"><a href="/showScanInfo?filename={{$name}}"><img src="/scanData/thumb/{{$name}}.png" alt=""></a></div>
						<div class="grid-content">
							<h4>{{$name}}</h4>
							<a href="/showScanInfo?filename={{$name}}"><h5 href="/showScanInfo?filename={{$name}}">查看详情</h5></a>
						</div>
						<div class="grid-more">
							<div class="icon ice-close-line" onclick="askForDelete('{{$name}}')"><span></span></div>
						</div>
					</div>
				</div>
				{{end}}
			</div>
		</div>
	</section>
</div>
<script>
	var isProcessEnd = false
	var isShow = false
	var process_Interval = 0

	// 开始启动扫描
    async function startScan() {
		// 定时更新进度条
		process_Interval = setInterval(updateProgressBar, 1000); // 1秒
		// 获取设备号
		var deviceValue = ice('#scan-device').val();
		// 获取分辨率
		var dpiValue = ice('#scan-dpi').val();
		// 获取扫描模式
		var modeValue = ice('#scan-mode').val();
		// 获取导出文件名
		var fileName = ice('#scan-filename').val();
		//判断文件名是否为空，为空则使用日期作为名字
		if (fileName == "") {
			//取当前日期
			let nowTime = new Date()
			fileName = this.formaData(nowTime)
			console.log("检测到文件名为空，使用日期为文件名:%s", fileName);
		};
        console.log("启动扫描中...\n当前设备:%s  当前使用分辨率:%s  当前模式:%s  当前文件名:", deviceValue ,dpiValue, modeValue, fileName);
		document.getElementById("scan-process").style.display="";//显示进度条
		await this.sendScanSettingPOST(deviceValue,dpiValue,modeValue,fileName);
    };

	//将扫描参数发送至go后端
	async function sendScanSettingPOST(deviceValue,dpiValue,modeValue,fileName){
		console.log("发送扫描参数至后端...\n",deviceValue,dpiValue,modeValue,fileName);
		//传对象
		await axios({
        url: '/SANEScanStart',
        method: 'post',
        data: {
            "device": deviceValue,
			"dpi": dpiValue,
			"mode": modeValue,
			"filename": fileName
        }
    })
        .then(function (response) {
            console.log("前端收到回复:",response.data)
        }).catch(function (err) {
            console.log(err)
        });
	}

	//用于格式化时间日期
	function formaData(timer) {
        const year = timer.getFullYear()
        const month = timer.getMonth() + 1 // 由于月份从0开始，因此需加1
        const day = timer.getDate()
        const hour = timer.getHours()
        const minute = timer.getMinutes()
        const second = timer.getSeconds()
        return `${pad(year, 4)}-${pad(month)}-${pad(day)}_${pad(hour)}:${pad(minute)}:${pad(second)}`
    }
    // 定义具体处理标准
    // timeEl 传递过来具体的数值：年月日时分秒
    // total 字符串总长度 默认值为2
    // str 补充元素 默认值为"0"
    function pad(timeEl, total = 2, str = '0') {
        return timeEl.toString().padStart(total, str)
    }

	//用于更新进度条	
	function updateProgressBar() {
		axios.get('/GetProcess')
			.then(response => {
				var progress = response.data.scanProcess;
				console.log("进度条信息%:",progress);
				var isShowstr = response.data.isProgressExist;
				var isScanEND = response.data.ScanEnd;
				if (isShowstr == "0"){
					console.log("进度条信息不存在");
				    //隐藏进度条
					document.getElementById("scan-process").style.display="none";//隐藏进度条
					//显示首次加载图标
					document.getElementById("box-loading").style.display="";
					if(isScanEND == "1" && isShow == false){
						//隐藏首次加载图标
						document.getElementById("box-loading").style.display="none";
						ice.popup({title:'提示', content:'扫描完成',yes:()=>refreshWeb(),no:()=>refreshWeb()})
						// clearInterval(process_Interval); //清除定时器
						// location.reload(); // 刷新页面
						isShow = true;
					}
				}else{
					const progressBar = document.getElementById('scan-processBar');
					progressBar.style.width = progress + '%'; // 更新进度条的宽度
					console.log("进度条宽度:",progressBar.style.width);
					progressBar.textContent = progress + '%'; // 更新显示的文本内容
					if(progress == 100.00 && isShow == false){
						isProcessEnd = true;
						document.getElementById("scan-process").style.display="none";//隐藏进度条
						document.getElementById("box-loading").style.display="none";//隐藏首次加载图标
						ice.popup({title:'提示', content:'扫描完成',yes:()=>refreshWeb(),no:()=>refreshWeb()})
						// clearInterval(process_Interval); //清除定时器
						// location.reload(); // 刷新页面
						isShow = true;
				}
				}
			})
			.catch(error => {
				console.error('Error:', error);
			});
	}

	const refreshWeb = () =>{
		clearInterval(process_Interval); //清除定时器
		location.reload(); // 刷新页面
		isShow = true;
	}

	const askForDelete = (filename) => {
	ice.popup({
		content:'是否删除该文件 ?',
		yes: () => askForDelete_yes(filename) // 将函数包装在一个匿名函数内
	})
   }

   const askForDelete_yes = (filename) =>{
	// filename = 'test'
	//删除文件
	console.log("删除文件...")
	//传对象
	axios({
        url: '/remove?filename='+filename,
        method: 'get',
    })
        .then(function (response) {
            console.log("前端收到回复:",response.data)
			if (response.data.status == '200'){
				ice.pop({
					content:'删除文件成功',
				})
			// 等待3秒后跳转到首页
			setTimeout(() => {
				console.log("延时3秒");
				window.location.href = '/SANEScan';
			}, 3000);
			}
        }).catch(function (err) {
            console.log(err)
        });
   }

	// const getScanDeviceList = () => {
	// 	console.log("开始获取设备列表")
	// 	axios.get('/getDevicesList').then(response => {
	// 		console.log("前端收到的设备列表",response)
	// 		if(response.data.status == 200){
	// 			var formattedList = response.data.list.map(item => {
	// 				return {
	// 					value: item.Value,
	// 					name: item.Name
	// 				};
	// 			});
	// 			console.log("整理后的选择框内容表:",formattedList)
	// 			// ice('#scan-device').select(formattedList);
	// 			// ui.setSelect("#scan-device",formattedList)
	// 			var selectElement = document.getElementById('scan-device');
	// 			// 清空当前所有选项
	// 			selectElement.innerHTML = '';

	// 			formattedList.forEach(item => {
	// 				var option = document.createElement('option');
	// 				option.value = item.value;
	// 				option.text = item.name;
	// 				selectElement.add(option);
	// 			});
	// 			console.log(ice('#scan-device').html());
	// 		}else{
	// 			clearInterval(getScanDeviceListID)
	// 		}
	// 	})
			
	// }
	// var getScanDeviceListID = setInterval(getScanDeviceList, 20000);
	// getScanDeviceList()
	</script>
	<style>
		.boxLoading {  
  width: 50px;
  height: 50px;
  margin: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
.boxLoading:before {
  content: '';
  width: 50px;
  height: 5px;
  background: #fff;
  opacity: 0.7;
  position: absolute;
  top: 59px;
  left: 0;
  border-radius: 50%;
  animation: shadow .5s linear infinite;
}
.boxLoading:after {
  content: '';
  width: 50px;
  height: 50px;
  background: #e04960;
  animation: animate .5s linear infinite;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 3px;
}
@keyframes animate {
  17% {
    border-bottom-right-radius: 3px;
  }
  25% {
    transform: translateY(9px) rotate(22.5deg);
  }
  50% {
    transform: translateY(18px) scale(1, .9) rotate(45deg);
    border-bottom-right-radius: 40px;
  }
  75% {
    transform: translateY(9px) rotate(67.5deg);
  }
  100% {
    transform: translateY(0) rotate(90deg);
  }
}
@keyframes shadow {
  0%, 100% {
    transform: scale(1, 1);
  }
  50% {
    transform: scale(1.2, 1);
  }
}
	</style>
</body>
</html>

